#!/usr/bin/env bash
set -e
set -o pipefail

handle_error() {
    local exit_code=$?
    echo "Error occurred in script at line: ${1} with exit code: ${exit_code}"
    exit $exit_code
}

trap "handle_error ${LINENO}" ERR

function running_qemu() {
    {
        python3 build/works/packet/qemu_shells/vemake_1711.py &
        QEMU_PID=$!
        sleep 30  # 等待QEMU初始化
    } > qemu_start.log 2>&1

    # 验证QEMU是否运行
    if ! ps -p $QEMU_PID > /dev/null; then
        echo "❌ QEMU启动失败"
        exit 1
    fi
    echo "✅ QEMU已启动(PID:$QEMU_PID)"
}

function download_testing_code() {
    cd ~
    rm -rf QA
    git clone https://gitcode.com/openUBMC/QA.git
    cd ~/QA/Robot_Framework/
}

function smoke_testing() {
    python3 smoke_test/install_dependency.py
    ps aux | grep qemu
    python3 smoke_test/execute.py
    python3 smoke_test/testing.py
}

function build_bmc_cpio() {
    cd $cur_path

    if ! bingo build -sc qemu; then
        echo "bingo build failed, printing temp/log/task.log"
        if [ -f temp/log/task.log ]; then
            cat temp/log/task.log
        fi
        exit 1
    fi

    # 检查output/packet/inner有没有仿真镜像包.cpio.gz包
    cpio_files=$(ls output/packet/inner/*.cpio.gz 2>/dev/null | wc -l)
    if [ "$cpio_files" -eq 0 ]; then
        echo "❌ 错误：未找到任何.cpio.gz包文件"
        echo "当前目录内容: "
        ls -la output/packet/inner/
        exit 1
    fi

    echo "manifest仓的output目录内容: "
    ls -l output/packet/inner/
}

# 1.prepare env
echo "======start to prepare env======"
cur_path=$(pwd)

chmod +x /root/repo/ci-repos/.common_scripts/common.sh
source /root/repo/ci-repos/.common_scripts/common.sh
prepare_git $1 $2
prepare_conan2 $3 $4
prepare_bingo

# 2. 下载conan缓存
echo "======conan cache====="
prepare_conan_cache

# 3. 构建仿真镜像包
echo "======Start build bmc simulation mirror package====="
build_bmc_cpio

# 4.运行qemu（后台运行+日志记录）
echo "======Start running qemu===="
running_qemu

# 5.下载测试代码
# 扩展性：未来社区开发者可以替换为自己的自动测试代码仓并在里面执行冒烟测试脚本
echo "======Download test code===="
download_testing_code

# 6.进行冒烟测试
# 冒烟测试脚本是存放在自动测试代码仓的
echo "======Start smoke testing===="
smoke_testing